package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.base.Result;
import com.example.demo.entity.AgriProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.base.KaisaUtil;


@RestController
@RequestMapping("/code")
public class CodeController {

    int key = 2;
    /**
     * 加密
     * @param comId 商品码
     * @param marketId 超市代码
     * @return
     */
    @GetMapping("/in")
    public Result<?> enCode(@RequestParam String comId,
                            @RequestParam String marketId) {
        // TODO 初始化处理
        String l = String.valueOf(comId.length());
        String str = comId+marketId+l;
        // TODO 字符串加密
        String result = KaisaUtil.enCode(str, key);
        return Result.success(result);
    }

    /**
     * 解密
     * @param code
     * @return
     */
    @GetMapping("/out")
    public Result<?> deCode(@RequestParam String code) {
        // todo 先解密
        String str = KaisaUtil.deCode(code, key);
        for(int i=0; i<str.length(); i++){
            if(!Character.isDigit(str.charAt(i))){
                return Result.error(0,"请检查防伪溯源码格式");
            }
        }
        // TODO 获取最后一位字符，代表商品码长度
        int index = Integer.parseInt(str.substring(str.length()-1));
        if(index == 0)
            return  Result.error(0,"请检查防伪溯源码格式");
        // TODO 抛弃最后一位字符
        str = str.substring(0, str.length()-1);
        // TODO 截取获取商品码于超市码
        String comId = str.substring(0,index);
        String marketId = str.substring(index);
        KaisaUtil.Res result = new KaisaUtil.Res();
        result.setV1(comId);
        result.setV2(marketId);
        return Result.success(result);
    }
}
